package com.nycreativity.elecreativity.config.webconfigure;

import com.fasterxml.jackson.databind.ObjectMapper;
import com.nycreativity.elecreativity.entity.cons.CommonURLConstants;
import com.nycreativity.elecreativity.interceptor.AliPayInterceptor;
import com.nycreativity.elecreativity.interceptor.MyInterceptor;
import com.nycreativity.elecreativity.interceptor.WxPayInterceptor;
import lombok.extern.slf4j.Slf4j;
import org.jetbrains.annotations.NotNull;
import org.springframework.context.annotation.Bean;
import org.springframework.context.annotation.Configuration;
import org.springframework.context.annotation.Primary;
import org.springframework.http.converter.json.Jackson2ObjectMapperBuilder;
import org.springframework.web.servlet.config.annotation.CorsRegistry;
import org.springframework.web.servlet.config.annotation.InterceptorRegistry;
import org.springframework.web.servlet.config.annotation.WebMvcConfigurer;


/**
 * @author sxt
 * @version : 1.0.0
 */
@Configuration
@Slf4j
public class WebMvcConfig implements WebMvcConfigurer {

    @Bean
    public WebMvcConfigurer corsConfigurer() {
        return new WebMvcConfigurer() {
            @Override
            public void addCorsMappings(@NotNull CorsRegistry registry) {
                registry.addMapping("/**")
                        .allowedOriginPatterns("*")
                        .allowedHeaders("*")
                        .allowedMethods("POST", "GET", "PUT", "OPTIONS", "DELETE", "PATCH")
                        .maxAge(3600)
                        .exposedHeaders("access-control-allow-headers", "access-control-allow-methods", "access-control-allow-origin", "access-control-max-age", "X-Frame-Options")
                        .allowCredentials(true);
            }
        };
    }

    @Bean(name = "objectMapper")
    @Primary
    public ObjectMapper addObjectMapper(Jackson2ObjectMapperBuilder builder) {
        return builder.createXmlMapper(false).build();
    }

    @Override
    public void addInterceptors(InterceptorRegistry registry) {

        //自行测试的时候可以把这个关掉
        registry.addInterceptor(new MyInterceptor())
                .addPathPatterns("/**")
//                .excludePathPatterns(CommonURLConstants.ALIPAY_PREFIX + "/**")
//                .excludePathPatterns(CommonURLConstants.WXPAY_PREFIX + "/**")
                .excludePathPatterns("/swagger-resources/**", "/webjars/**", "/v2/**", "/swagger-ui.html/**");
        //支付宝的拦截器
        registry.addInterceptor(new AliPayInterceptor()).addPathPatterns(CommonURLConstants.ALIPAY_PREFIX + "/**");
        //微信支付的拦截器
        registry.addInterceptor(new WxPayInterceptor()).addPathPatterns(CommonURLConstants.WXPAY_PREFIX + "/**");

    }
}

